<?php
/**
 * 文件描述
 * Created on 2021/8/9 11:37
 * Create by LZH
 */

namespace App\Model;

use App\Model\Admin\AdminModel;
use EasySwoole\Mysqli\QueryBuilder;
use EasySwoole\ORM\AbstractModel;
use EasySwoole\ORM\DbManager;

class BaseModel1 extends AbstractModel
{

    public function __construct()
    {
        parent::__construct();
        if (empty($this->tableName)) {
            throw new \Exception("table error");
        }
    }

    /**
     * 获取单条数据
     * @param string $field [字段]
     * @param array $where [搜索条件]
     * @param array $order
     * @return array|false [type]             [description]
     * @throws \EasySwoole\Mysqli\Exception\Exception
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     */
    public function getOne(string $field = '*', array $where = [], array $order = ['id', 'desc'])
    {
        $info = $this->field($field)
            ->where($where)
            ->order($order[0], $order[1])
            ->get()
            ->toArray();

        if ($info) {

            // 获取系统人员缓存
            $AdminModel = new AdminModel();
            $userAll = $AdminModel->getAll();

            // 添加人
            if (isset($info['create_id']) && $info['create_id']) {
                $info['create_user_name'] = $userAll[$info['create_user']]['realname'];
            }
            // 添加时间
            if (isset($info['create_time']) && $info['create_time']) {
                $info['create_time'] = date('Y-m-d H:i:s', $info['create_time']);
            }

            // 更新人
            if (isset($info['update_id']) && $info['update_id']) {
                $info['update_user_name'] = $userAll[$info['update_user']]['realname'];
            }
            // 更新时间
            if (isset($info['update_time']) && $info['update_time']) {
                $info['update_time'] = date('Y-m-d H:i:s', $info['update_time']);
            }

            // 状态
            if (isset($info['status']) && $info['status'] && isset($this->status)) {
                $info['status_name'] = $this->status[$info['status']];
            }
        }

        if (empty($info)) {
            return false;
        } else {
            return $info;
        }
    }

    /**
     * @throws \Throwable
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \EasySwoole\Mysqli\Exception\Exception
     */
    public function getOneById($id)
    {
        return $this->getOne('*', ['id' => $id]);
    }

    /**
     * 获取分页列表
     * @param string $field [字段]
     * @param array $where [搜索条件]
     * @param int $page [页数]
     * @param int $pageSize [条数]
     * @param array $order
     * @return array [type]             [description]
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     */
    public function getPageList(string $field = '*', array $where = [], int $page = 1, int $pageSize = 10, array $order = ['id','desc']): array
    {
        $result = $this
            ->withTotalCount()
            ->order($order[0], $order[1])
            ->field($field)
            ->where($where)
            ->page($page, $pageSize)
            ->all();
        $count = $this->lastQueryResult()->getTotalCount();
        $lists = $this->lastQueryResult()->getResult();

        // $list = $lastResult->getResult();
        return ['count' => $count, 'lists' => $lists];
    }

    public function getCount(string $field = 'id', array $where = [])
    {
        $result = $this->where($where)->count();

        return $result;
    }

    public function getAll(string $field = '*', array $where = [], array $order = ['id', 'desc'], string $group='')
    {
        $result = $this
            ->field($field)
            ->order($order[0], $order[1])
            ->where($where)
            ->group($group)
            ->all()->toArray();

        $result = array_column($result, null, $this->primaryKey);

        return $result;
    }

    public function add($data)
    {
        $result = $this->data($data)->save();

        return $result;
    }

    /**
     * 进行批量修改数据
     * @param  array  $data  [description]
     * @param  array  $where [description]
     * @param  int    $exp   [修改的数据是否加上老数据]
     * @return [type]        [description]
     */
    public function updateMulti(array $data, array $where, $exp=0)
    {
        if (!is_array($where)) {
            return false;
        }

        if (count($data) != count($where)) {
            return false;
        }

        $wValue = array_values($where);
        $wFiled = array_keys($where);

        $strValue = '';
        $filed = '';
        $iCount = 0;
        $wSQL = array();
        $iSQL = 0;
        foreach ($data as $key=>$val) {
            $iSQL = count($val);
            if (!is_array($val)) {
                return false;
            }

            $jCount = 0;
            if (0 == $iCount) {
                foreach ($val as $key2=>$val2) {
                    $wSQL[$jCount] = sprintf("%s = CASE %s ", $key2, $wFiled[0]);
                    $jCount++;
                }
            }
            $jCount = 0;
            foreach ($val as $key2=>$val2) {
                if ($exp == 1) {
                    $wSQL[$jCount] .= sprintf("WHEN '%s' THEN %s ", $wValue[$iCount], $val2);
                } else {
                    $wSQL[$jCount] .= sprintf("WHEN '%s' THEN '%s' ", $wValue[$iCount], $val2);
                }

                $jCount++;
            }

            $iCount++;
        }
        $sql = "UPDATE ".$this->tableName." SET ";
        for ($i=0; $i < $iSQL; $i++) {
            if ($i == ($iSQL-1)) {
                $sql .= $wSQL[$i]."END ";
            } else {
                $sql .= $wSQL[$i]."END, ";
            }
        }
        $this->filter_filed_value($wValue);

        $sql .= sprintf("WHERE %s IN (%s)", $wFiled[0], $wValue);
        $queryBuild = new QueryBuilder();
        // 支持参数绑定 第二个参数非必传
        $queryBuild->raw($sql);
        // $queryBuild->raw("select * from test where name = 'siam'");

        // 第二个参数 raw  指定true，表示执行原生sql
        // 第三个参数 connectionName 指定使用的连接名，默认 default
        $model = DbManager::getInstance()->query($queryBuild, true, 'default');

        $result = $model->getResult();
        return $result;
    }

    /**
     * 给字段值两边加引号，保证数据安全，并对特有内容进行转义
     * @param $value array
     * @return
     */
    private function filter_filed_value(&$value)
    {
        if (is_array($value)) {
            $new_value = array();
            foreach ($value as $k => $v) {
                $new_value[$k] = '\''.$v.'\'';
            }

            $value = implode(',', $new_value);
        } else {
            $value = '\''.$value.'\'';
        }
    }

    /**
     * 批量插入数据返回数组形式的插入id值
     * @param array $multiInsertData [description]
     * @return array|false [type]                  [description]
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     */
    public function insertMulti(array $multiInsertData)
    {
        $builder = new QueryBuilder();

        $builder->insertAll($this->tableName, $multiInsertData);
        $model = DbManager::getInstance()->query($builder, true, 'default');

        //第一个插入的id
        $id = $model->getLastInsertId();
        //sql语句执行结果
        $result = $model->getResult();
        //插入的行数
        $count = $model->getAffectedRows();

        if (!$result) {
            return false;
        } else {
            $ids = [];
            for ($i=0; $i < $count; $i++) {
                $ids[] = $id+$i;
            }
        }

        return $ids;
    }

    /**
     * 获取数据然后转换成id=>name的形式
     * @param  [type] $where [description]
     * @return array [type]        [description]
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     */
    public function getIDName($where)
    {
        $result = $this
            ->field('id,name')
            ->where($where)
            ->all();

        $lists = $this->lastQueryResult()->getResult();

        //返回的数据
        $data = [];
        foreach ($lists as $key => $value) {
            $data[$value['id']] = $value['name'];
        }

        return $data;
    }

    /**
     * 获取数据然后转换成id=>name的形式
     * @param  [type] $where [description]
     * @return mixed [type]        [description]
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     */
    public function getIDNameArr($where)
    {
        $result = $this
            ->field('id,name')
            ->where($where)
            ->all();

        $lists = $this->lastQueryResult()->getResult();

        return $lists;
    }


    public function getLastQuerySql()
    {
        var_dump($this->lastQuery()->getLastQuery());
    }

    protected function getLastResult(): array
    {
        //连表无法返回连表的数据
        $lastResult = $this->lastQueryResult();
        return $lastResult->getResult();
    }


}
